package com.czt.mail.kafka;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;

/**
 * @author czt
 * @version 1.0
 * {@desc}
 * @date 2024/10/8 16:15
 */
public class ProducerQuickStart {
    public static void main(String[] args) {

        //1.kafka连接配置信息
        Properties properties = new Properties();
        //连接信息
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092");
        //key序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //value序列化
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //确认机制，acks  0无需确认，1主节点确认，all全部节点确认
        properties.put(ProducerConfig.ACKS_CONFIG, "all");
        //重试机制，retries
        properties.put(ProducerConfig.RETRIES_CONFIG, 10);
        //压缩算法，gzip,lz4,snappy
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "gzip");
        //2.创建kafka生产者对象
        KafkaProducer<String,String> producer = new KafkaProducer<>(properties);

        //3.发送消息
        /**
         * 第一个参数：topic
         * 第二个参数：消息的key
         * 第三个参数：消息的value
         */
        ProducerRecord<String, String> kvProducerRecord = new ProducerRecord<String, String>("topic","key-001","hello kafka");
        //同步发送
        //producer.send(kvProducerRecord);
        //异步发送
        producer.send(kvProducerRecord, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if (e != null) {
                    System.out.println("异步发送消息发生异常了");
                }
                System.out.println("recordMetadata = " + recordMetadata.offset());
            }
        });
        //4.关闭消息通道，必须关闭，否则发送不成功
        producer.close();
    }
}
